﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Configuration;
using IHISCETeim.BLL;
using IHISCETeim.Library;
using IHISCETeim.Model;
using System.Threading;
namespace IHISCETeim.SendEMailSvr
{
    public partial class AutoSendEMail : ServiceBase
    {
        public AutoSendEMail()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 获取周期时间
        /// </summary>
        /// <returns></returns>
        private int GetSnycInterval()
        {
            int SnycInterval = 0;
            try
            {
                SnycInterval = Convert.ToInt32(ConfigurationManager.AppSettings["SnycInterval"]);
            }
            catch
            {
                SnycInterval = 5;
            }
            return SnycInterval * 1000 ;
        }

        protected override void OnStart(string[] args)
        {
            Common.WriteLog("IHISCE信息化管理系统邮件自动发送服务已启动!");
            timer2.Interval = GetSnycInterval();

            //timer2.Interval = 1000 * 10;
            timer2.Enabled = true;
            timer2.Start();

            QltySendTimer.Enabled = true;
            QltySendTimer.Start();


        }

        protected override void OnStop()
        {
            timer2.Enabled = false;
            timer2.Stop();

            QltySendTimer.Enabled = false;
            QltySendTimer.Stop();

            Common.WriteLog("信息化管理系统邮件自动发送服务已停止!");
        }
        bool Exeed = false;
      
        /// <summary>
        /// 定时执行短信发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer2_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (!Exeed)
            {
              //  Common.WriteLog("开始扫描需发送邮件");

                Exeed = true;
                try
                {
                   // StartScan();
                  // InitScanVar();

                }
                catch (System.Exception err)
                {
                   Common.WriteLog("扫描出错:"+err.Message);

                }
                try
                {
                    
                    StartSend();
                }
                catch (System.Exception err)
                {
                    Common.WriteLog("发送出错:" + err.Message);

                }

                Exeed = false;
                Common.WriteLog("结束扫描需发送邮件");
            }
        }

        bool QltyExeed = false;
        private void QltySendTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (!QltyExeed)
            {
                  Common.WriteLog("2开始扫描需发送邮件");

                QltyExeed = true;

                try
                {



                    List<SEMailListInfo> list = new List<SEMailListInfo>();
                    list = SEMailListController.GetAllNeedSendList(1);
                    if (list.Count <= 0)
                    {
                        return;
                    }
                    int sendCount = 0;//如果发送超过100封，则暂停1分钟
                    foreach (SEMailListInfo obj in list)
                    {
                        if (obj.MailTo == ";")
                            continue;

                        string restr = Mail.QltySendMail(obj.MailTo, obj.Subject, obj.Body);
                        if (string.IsNullOrEmpty(restr))
                        {
                            Common.WriteLog("2[成功]发送功.主题为[" + obj.Subject + "],系统ID为[" + obj.ID.ToString() + "]");
                            SEMailListController.UpdateSend(obj.ID);
                        }
                        else
                        {
                            Common.WriteLog("2[失败]发送失败,原因:[" + restr + "].主题为[" + obj.Subject + "],系统ID为[" + obj.ID.ToString() + "]");
                            //2016-05-27　加入错误处理，如果发送失败，有可能会重复发送，固只提醒管理员
                            Mail.SendMail(ConfigurationManager.AppSettings["adminMail"], "邮件发送失败提醒", string.Format("SEMailList表ID为{0},请检查相应的邮箱是否正常", obj.ID));
                            SEMailListController.UpdateSend(obj.ID);
                        }
                        Thread.Sleep(500);//停500豪秒
                        sendCount++;
                        if (sendCount >= 100)
                        {
                            //   Thread.Sleep(1000 * 60);//停1份钟
                            sendCount = 0;
                        }
                    }

                    Common.WriteLog("---------------------------------------------------------------------------------");
                }
                catch (System.Exception err)
                {
                    Common.WriteLog("2发送出错:" + err.Message);

                }
                finally {
                    QltyExeed = false;
                }

                QltyExeed = false;
                Common.WriteLog("2结束扫描需发送邮件");
            }


        }
        /// <summary>
        /// 开始执行邮件发送程序
        /// </summary>
        public void StartSend()
        {

            List<SEMailListInfo> list = new List<SEMailListInfo>();
            list = SEMailListController.GetAllNeedSendList();
            if (list.Count <= 0)
            {
                return;
            }
            int sendCount = 0;//如果发送超过100封，则暂停1分钟
            foreach (SEMailListInfo obj in list)
            {
                if (obj.MailTo == ";")
                    continue;

                string restr=   Mail.SendMail(obj.MailTo, obj.Subject, obj.Body);
                if (string.IsNullOrEmpty(restr))
                {
                    Common.WriteLog("[成功]发送功.主题为[" + obj.Subject + "],系统ID为[" + obj.ID.ToString() + "]");
                    SEMailListController.UpdateSend(obj.ID);
                }
                else
                {
                    Common.WriteLog("[失败]发送失败,原因:["+restr+"].主题为[" + obj.Subject + "],系统ID为[" + obj.ID.ToString() + "]");
                    //2016-05-27　加入错误处理，如果发送失败，有可能会重复发送，固只提醒管理员
                    Mail.SendMail(ConfigurationManager.AppSettings["adminMail"], "邮件发送失败提醒", string.Format("SEMailList表ID为{0},请检查相应的邮箱是否正常",obj.ID));
                    SEMailListController.UpdateSend(obj.ID);
                }
                Thread.Sleep(500 );//停1秒
                sendCount++;
                if (sendCount >= 100)
                {
                   // Thread.Sleep(1000 * 60);//停1份钟
                    sendCount = 0;
                }
            }
           
            Common.WriteLog("---------------------------------------------------------------------------------");
        }

        /// <summary>
        /// 开始执行扫描需发送邮件
        /// </summary>
        public void StartScan()
        {
           
           

            //2.生产部将生产的机器通知
           // EMailController.GetNeedSendSCGLOPrject();
            
          
           
            //5.DWF图纸审批相关
           // EMailController.JSDWFApplyGetNeedSendEmail();
           


           
          
          
        }
        /// <summary>
        /// SAP借件归还提醒当天是否已扫描,每天扫一次,false未扫，TRUE已扫
        /// </summary>
        public static bool SAP_GetJieJianGuiHuanAlertScan=false;

        private string lastScanDate = "";
        private void InitScanVar()
        {
            Common.WriteLog("InitScanVar-开始");
            if (string.IsNullOrEmpty(lastScanDate))
            {
                lastScanDate = DateTime.Now.ToString("yyyy-MM-dd");
            }
            if (DateTime.Now.ToString("yyyy-MM-dd") == lastScanDate)
                return;
            else
            {
                lastScanDate = DateTime.Now.ToString("yyyy-MM-dd");

                SAP_GetJieJianGuiHuanAlertScan = false;
            }
            Common.WriteLog("InitScanVar-结速");
            Common.WriteLog("SAP_GetJieJianGuiHuanAlertScan"+ SAP_GetJieJianGuiHuanAlertScan.ToString());
        }

        private void SendPToolingChargeNoBomtimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DateTime dtnow = DateTime.Now;
            if (dtnow.Hour != 8 || dtnow.Minute != 42)
            {
                return;
            }
            //if ((dtnow.Second == 10 ))
            //{
            //    return;
            //}
            //0.处理模具分摊中基准BOM不用的物料清单
            EMailController.SendPToolingChargeNoBom();
        }

        private void GetPToolingChargeExpireListtimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DateTime dtnow = DateTime.Now;
            if (dtnow.Hour != 8 || dtnow.Minute != 55)
            {
                return;
            }

            //if ((dtnow.Second == 10 || dtnow.Second == 11 || dtnow.Second == 12 || dtnow.Second == 13 || dtnow.Second == 14 || dtnow.Second == 15))
            //{
            //    return;
            //}

            //1.模具费分摊
            EMailController.GetPToolingChargeExpireList();
        }

        private void GetMonthNeedRemindtimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DateTime dtnow = DateTime.Now;
            if (dtnow.Hour != 8 || dtnow.Minute != 35)
            {
                return;
            }
            //3.证件年审管理 月发送,每月发送一次
            EMailController.GetMonthNeedRemind();
        }

        private void GetDayNeedRemindtimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DateTime dtnow = DateTime.Now;
            if (dtnow.Hour != 8 || dtnow.Minute != 45)
            {
                return;
            }
            //4.证件年审管理 天发送,每天发送一次
            EMailController.GetDayNeedRemind();
        }

        private void SBOMChangeOITMtimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DateTime dtnow = DateTime.Now;
            if (dtnow.Hour < 9 || dtnow.Hour > 17)
            {
                return;
            }

            if (dtnow.Minute != 30)
            {
                return;
            }
           
            //6.BOM变更所需物料
            EMailController.SBOMChangeOITM();
        }

        private void AgentQltySendWarnInputDateEmailtimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DateTime dtnow = DateTime.Now;
            if (dtnow.DayOfWeek == DayOfWeek.Sunday)
                return;//周日不发
            if (dtnow.DayOfWeek == DayOfWeek.Saturday)
                return;//周6不发

            if (dtnow.Hour != 9)
            {
                return;
            }
            if (dtnow.Minute != 30)
            {
                return;
            }
            //if (dtnow.Second != 10 || dtnow.Second != 11 || dtnow.Second != 12)
            //{
            //    return;
            //}
            //7.经销商平台 品情
            EMailController.AgentQltySendWarnInputDateEmail();
        }

        private void SAP_GetDZBtimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DateTime dtnow = DateTime.Now;
            if (dtnow.DayOfWeek != DayOfWeek.Monday || dtnow.Hour != 8)
            {
                return;//每周一7点发送。
            }
            if (dtnow.Minute != 30 )
            {
                return;
            }
            //9.2015-02-06 SAP 获取呆滞品信息发送
            EMailController.SAP_GetDZB();
        }

        private void SAP_GetJieJianGuiHuanAlerttimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DateTime dtnow = DateTime.Now;

            if (dtnow.Hour != 9)
            {
                return;
            }


            if (dtnow.Minute != 1 )
            {
                return;
            }
            //10.2016-03-22 SAP借件归还提醒
            EMailController.SAP_GetJieJianGuiHuanAlert();
        }

      
    }
}
